<template>
	<view>
		<view>
			<table-title content="交房办理表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="租户名称" :value="userMsg.userCompany"></view-item>
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor"></view-item>
				<view-item name="房间号" :value="userMsg.userRoom" :isLast="true"></view-item>
			</view>
<!-- 			<small-title v-if="state==='待申请'" content="选择楼盘"></small-title>
			<view v-if="state==='待申请'" class="small-title">
				<select-lay :value="tvalBuilding" name="name" :options="datalistBuilding" @selectitem="selectitemBuilding"></select-lay>
			</view> -->
			<small-title :isNeed="true" v-if="status===-1" content="选择楼盘"></small-title>
			<view v-if="status===-1" class="small-title">
				<select-lay :zindex="2" :value="tvalBuilding" name="build" :options="datalistBuilding" @selectitem="selectitemBuilding"></select-lay>
			</view>
			<small-title :isNeed="true" v-if="status===-1" content="选择租户"></small-title>
			<view v-if="status===-1" class="small-title">
				<select-lay :value="tvalUser" name="name" :options="datalistUser" @selectitem="selectitemUser"></select-lay>
			</view>
			<view v-if="status >= 0">
				<small-title :isNeed="true" content="租赁合同文件"></small-title>
				<view v-for="(item,index) in pdfFileId" class="download-text" @click="downloadFile(1,index)">租赁合同{{index + 1}}.pdf</view>
				<button v-if="status===0 && userRightDetail.renewal.contractCommRight" class="add-button" @click="uploadFile(1)">上传文件</button>
				<small-title :isNeed="true" content="租赁到期日期"></small-title>
				<view class="small-title">
					<uni-datetime-picker type="date" :value="endDate" :start="currentDate" end="" @change="change" :disabled="!(status===0 && userRightDetail.renewal.contractCommRight)"></uni-datetime-picker>
				</view>
				<small-title :isNeed="true" content="合同签约日期"></small-title>
				<view class="small-title">
					<uni-datetime-picker type="date" :value="signDate" start="" :end="currentDate" @change="signChange" :disabled="!(status===0 && userRightDetail.renewal.contractCommRight)"></uni-datetime-picker>
				</view>
				<small-title :isNeed="true" content="租赁面积(㎡)"></small-title>
				<input v-if="status===0" class="price-input" v-model="measureArea" @input="check" type="number" :disabled="!(status===0 && userRightDetail.renewal.contractCommRight)" placeholder="请输入租赁面积" />
				<a v-if="status === 0">㎡</a>
				<view v-if="status > 0" class="cost-all">{{measureArea}} ㎡</view>
				<small-title :isNeed="true" content="月租金单价(元)"></small-title>
				<input v-if="status===0" class="price-input" v-model="unitPrice" @input="checkPrice" type="number" :disabled="!(status===0 && userRightDetail.renewal.contractCommRight)" placeholder="请输入金额" />
				<a v-if="status === 0">元</a>
				<view v-if="status > 0" class="cost-all">{{unitPrice}} 元</view>
			</view>
			<view v-if="status > 0">
				<small-title :isNeed="true" content="家私配置清单"></small-title>
				<view class="download-text" @click="downloadFile(0)">{{docxFileName}}</view>
				<button v-if="status===1 && userRightDetail.goodsRelease.right" class="add-button" @click="uploadFile(0)">上传文件</button>
			</view>
			<small-title content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="state==='待申请'" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="addOrder">发起交房</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===1 && userRightDetail.goodsRelease.right" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="reAddOrder">上传配置清单</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===0 && userRightDetail.renewal.contractCommRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="finish">上传合同</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" type="dialog">
		    <uni-popup-dialog mode="input" message="成功消息" title="请输入整改意见" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
		<l-file 
		    ref="lFile" 
			@up-success="upSuccess"
		></l-file>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE_2,
		syncGetOrder
	} from "../../../util/network.js"
	import {
		processHistoryList,
		getNowFormatDate
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				status:-1,
				processFlag:false,
				recordId: -1,
				processNo:'待分配',
				state: '',
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				goodList:[],
				docxFileId:-1,
				docxFileName:'家私配置清单.docx',
				pdfFileId:[],
				pdfFileName:[],
				nopassReasons:'',
				proccessListDefult:[],
				token:'',
				endDate:'',
				signDate:'',
				fileType:0,
				//模拟数据列表
				datalistUserbak: [],
				datalistUser: [],
				//模拟初始数据
				tvalUser: "value2",
				//模拟数据列表
				datalistBuilding: [],
				//模拟初始数据
				tvalBuilding: "value2",
				rentUserId:-1,
				measureArea:0,
				unitPrice:0,
				currentDate:'',
				userRightDetail:''
			}
		},
		methods: {
			check: function(index) {
				//正则表达试
				let temp = (this.measureArea.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				this.$nextTick(() => {
					this.measureArea= temp
				})
			},
			checkPrice: function(index) {
				//正则表达试
				let temp = (this.unitPrice.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				this.$nextTick(() => {
					this.unitPrice= temp
				})
			},
			selectitemUser(index, item) {
				console.log(item)
				if (index >= 0) {
					this.tvalUser = item.value;
					let userJson = JSON.parse(item.value)
					this.userMsg.userCompany = userJson.name
					this.userMsg.userBuilding = userJson.title
					this.userMsg.userFloor = userJson.floor
					this.userMsg.userRoom = userJson.houseNumber
					this.rentUserId = userJson.id
				} else {
					this.tvalUser = ""
				}
			},
			selectitemBuilding(index, item) {
				console.log(item)
				if (index >= 0) {
					this.tvalBuilding = item.value;
					this.datalistUser = []
					this.datalistUserbak.forEach(item => {
						if(parseInt(this.tvalBuilding) == JSON.parse(item.value).buildId){
							this.datalistUser.push(item)
						}
					})
				} else {
					this.tvalBuilding = ""
				}
			},
			change(value){
				this.endDate = value + " 23:59:59"
				console.log(this.endDate)
			},
			signChange(value){
				this.signDate = value + " 23:59:59"
				console.log(this.signDate)
			},
			open() {
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				this.$refs.popup.close()
				if(value == ""){
					uni.showModal({
						content:'意见不能为空',
						showCancel:false
					});
					this.$refs.popup.close()
				}else{
					this.nopassReasons = "需要整改，描述：" + value
					this.qfConfirm(1)
					// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
					// ...
					this.$refs.popup.close()
				}
			},
			
			upSuccess(e){
				console.log(e)
				if(this.fileType == 0){
					this.docxFileName = e.fileName
					this.docxFileId = e.data
				}else{
					this.pdfFileId.push(e.data)
				}
			},
			
			uploadFile(status){
				this.fileType = status
				this.$refs.lFile.upload({
				    // #ifdef APP-PLUS
				    //（app端必传）nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
				    currentWebview: this.$mp.page.$getAppWebview(),
				    // #endif
				    //替换为你的上传接口地址
				    url: `${ONLINE_SERVER_ADDRESS_BASE_2}/file/upload`,
				    // 服务端接收附件的key
				    name: 'file',
				    //根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
				    header: {
						'Authorization': this.token,
				        // 'Authorization': 'bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJ1c2VyTmFtZSI6',
				        // 'uid': '27682',
				        // 'client': 'app',
				        // 'accountid': 'DPOA9487'
				    },
				
				    // 限制选择附件的大小上限，默认10M
				    // maxSize: 20,
				
				    // 若需要在body单独添加附件名或附件大小如下方式传入组件：
				    // addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
				    // addSize: '后端要的附件大小字段key'
				
				    // body参数直接写key,value,如：
				    // date: '2020-1-1',
				    // key2: 'value2',
				});
			},
			
			downloadFile(fileType,index){
				let fileId = 0
				if(fileType == 0){
					fileId = this.docxFileId
				}else{
					fileId = this.pdfFileId[index]
				}
				if(!(parseInt(fileId) > 0)){
					uni.showModal({
						content:'找不到该文件,请检查是否已上传。',
						showCancel:false
					})
					return 0
				}
				this.$refs.lFile.download({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/file/download/` + fileId,
					token:this.token,
				})
				.then(path=>{
				    // 打开文件
				    this.$refs.lFile.open(path);
				});
			},

			
			finish(){
				console.log("[info]","重新发起交房：" + this.recordId)
				if(this.endDate == "" || this.pdfFileId.length == 0 || this.signDate == "" || this.measureArea <= 0 || this.unitPrice <= 0){
					uni.showModal({
						content:'请上传租赁合同并输入合同到期日期、签约日期、租赁面积及月租金单价',
						showCancel:false
					})
					return 0
				}
				let pdfFileId = JSON.stringify(this.pdfFileId).replace('[','').replace(']','')
				if(this.userRightDetail.renewal.primeAuth == 11){
					this.nopassReasons = "合同主管已完成租赁合同配置"
				}else{
					this.nopassReasons = "合同专员已完成租赁合同配置"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/handover/finish/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						fileId:pdfFileId,
						dueTime:this.endDate,
						signTime:this.signDate,
						measureArea:this.measureArea,
						unitPrice:this.unitPrice,
						commentMsg: this.nopassReasons                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起交房成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起交房调用失败")
					}
				})
			},
			
			reAddOrder(){
				console.log("[info]","重新发起交房：" + this.recordId)
				if(!(this.docxFileId > 0)){
					uni.showModal({
						content:'请上传家私清单配置表',
						showCancel:false
					})
					return 0
				}
				if(this.userRightDetail.knotCommission.primeAuth == 1){
					this.nopassReasons = "运营主管上传了家私配置清单"
				}else{
					this.nopassReasons = "楼层管家上传了家私配置清单"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/handover/bb-confirm/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						fileId:this.docxFileId,
						commentMsg: this.nopassReasons                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起交房成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起交房调用失败")
					}
				})
			},
			
			addOrder(){
				if(this.rentUserId == -1){
					uni.showModal({
						content:'请选择租户',
						showCancel:false
					})
					return 0
				}
				if(this.userRightDetail.knotCommission.primeAuth == 1){
					this.nopassReasons = "运营主管发起交房"
				}else{
					this.nopassReasons = "楼层管家发起交房"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/handover/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						userId:this.rentUserId,
						commentMsg: this.nopassReasons                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起交房成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起交房调用失败")
					}
				})
			},
			
			getOrder(){
				let a = syncGetOrder("handover/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 console.log("详细",res.data.data)
						 this.status = res.data.data.status
						 switch(this.status) {
						      case 0:
						         this.state = "待合同上传"
						         break;
						      case 1:
						         this.state = "待管家上传"
						         break;
						 	 case 2:
						         this.state = "待用户确认"
						 	    break;
						 	 case 3:
						         this.state = "用户已确认"
						 	    break;
						      default:
						         this.state = "待申请"
						 } 
						 this.userMsg.userCompany = res.data.data.createUserInfo.name
						 this.userMsg.userBuilding = res.data.data.createUserInfo.title
						 this.userMsg.userFloor = res.data.data.createUserInfo.floor
						 this.userMsg.userRoom = res.data.data.createUserInfo.houseNumber
						 this.processNo = res.data.data.processNo
						 try{
						 	let tempArray = res.data.data.contractFileId.split(',')
						 	tempArray.forEach((item,index) => {
						 		this.pdfFileId.push(item)
								let tempIndex = index + 1
								let temp ='租赁合同' + tempIndex + '.pdf'
						 	})
						 }catch(e){
						 	//TODO handle the exception
						 }
						 this.docxFileId = res.data.data.configFileId
						 try{
						 	this.endDate = res.data.data.dueTime.replace('T', ' ')
							this.signDate = res.data.data.signTime.replace('T', ' ')
						 }catch(e){
						 	//TODO handle the exception
						 }
						 if(this.status > 0){
							 this.measureArea = res.data.data.measureArea
							 this.unitPrice = res.data.data.unitPrice
						 }
						 this.proccessListDefult = processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
					}
				})
			},
			
			getUserList(){
				let _this = this
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/user/list`,
					header: {
						'Authorization': this.token,
					},
					data: {
						pageNo:0,
						pageSize:100,
					},
					method:'GET',
					success: function (res) {
						console.log("查询租户",res);
						if(res.data.code == 200){
							let resList = res.data.data.userList
							resList.forEach((item,key) => {
								let temp = {label: "",value: ""}
								temp.label = item.name + '(' + item.houseNumber + ')'
								temp.value = JSON.stringify(item)
								_this.datalistUserbak.push(temp)
								_this.getBuildingList(item)
							});
							_this.$forceUpdate()
						}
					},
					fail: (res) => {
						console.log("查询租户失败")
					}
				})
			},
			getBuildingList(item){
				let flag = true
				for (var i = 0; i < this.datalistBuilding.length; i++) {
					if(this.datalistBuilding[i].value == item.buildId){
						flag = false
						break
					}
				}
				if(flag){
					let temp = {}
					temp.label = item.title
					temp.value = item.buildId
					this.datalistBuilding.push(temp)
				}
			},
			
			back(){
				uni.navigateBack()
			},
		},
		onLoad(option) {
			//传入单号
			let  newdate=getNowFormatDate()
			this.currentDate = newdate
			if(uni.getStorageSync('userinfo') != null){
				this.userRightDetail = uni.getStorageSync("userRight")
				this.recordId = option.id
				this.token = uni.getStorageSync('token')
				this.getUserList()
				this.state = option.state
				// console.log(`${ONLINE_SERVER_ADDRESS_BASE_2}/goods-release/finish/` + this.recordId)
			}else{
				uni.navigateTo('../../login/login')
			}
		},
		mounted() {
			//如果是新建表单则不查询
			if(this.state != '待申请'){
				this.getOrder()
			}
		}
	}
</script>

<style>
	page{
		background-color: #ffffff
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.download-text {
	  -webkit-box-sizing: content-box;
	  -moz-box-sizing: content-box;
	  box-sizing: content-box;
	  border: none;
	  font: normal 16px/1 "Times New Roman", Times, serif;
	  color: rgba(18,25,232,1);
	  text-decoration: underline;
	  -o-text-overflow: ellipsis;
	  text-overflow: ellipsis;
	  margin-left: 60rpx;
	  margin-bottom: 10rpx;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
		width: 87%;
	}
	.price-input {
	  display: inline-block;
	  -webkit-box-sizing: content-box;
	  -moz-box-sizing: content-box;
	  box-sizing: content-box;
	  width: 50%;
	  padding: 9px 0 6px 20px;
	  border: 1px solid #b7b7b7;
	  -webkit-border-radius: 3px;
	  border-radius: 3px;
	  font: normal 16px/normal "Times New Roman", Times, serif;
	  color: rgba(0,142,198,1);
	  -o-text-overflow: clip;
	  text-overflow: clip;
	  background: rgba(252,252,252,1);
	  -webkit-box-shadow: 2px 2px 2px 0 rgba(0,0,0,0.2) inset;
	  box-shadow: 2px 2px 2px 0 rgba(0,0,0,0.2) inset;
	  text-shadow: 1px 1px 0 rgba(255,255,255,0.66) ;
	  -webkit-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
	  -moz-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
	  -o-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
	  transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
	  margin-left: 50rpx;
	  margin-right: 30rpx;
	}
	.cost-all{
		display: flex;
		margin-left: 8%;
		font-size: 30rpx;
	}
</style>
